//
//  PersonalViewController.m
//  TestApplication
//
//  Created by Hanlingyu on 16/9/14.
//  Copyright © 2016年 ltq. All rights reserved.
//

#import "PersonalViewController.h"
#import "TAMacro.h"
#import "SelfSizeTool.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "UIButton+WebCache.h"

#import "PersonAbstractModelContent.h"
#import "PersonalTableViewCell.h"

#import "PersonAbstractModel.h"
#import "PersonalViewModel.h"
#import "PersonChannelContent.h"
#import "PersonalChannelView.h"
#import "PostsDetailViewController.h"
#import "PersonChannelPosts.h"
#import "PostVoiceViewController.h"
@interface PersonalViewController ()
<
    UITableViewDelegate,
    UITableViewDataSource
>
/**
 *  Model
 */
@property (nonatomic, strong) PersonAbstractModel *personModel;
@property (nonatomic, strong) PersonalViewModel *personalViewModel;
@property (nonatomic, strong) NSMutableArray<PersonalViewModel *> *personalViewModelArray;
@property (nonatomic, strong) UIView *backViewForTableHeaderView;
@property (nonatomic, strong) UIImageView *backImageViewForTableHeaderView;
@property (nonatomic, strong) UIImageView *barImageView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UITableView *personalTableView;
@property (nonatomic, strong) UIView *personalTableHeaderView;

@property (nonatomic, strong) UIImageView *maskingImageView;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UIButton *headerImageButton;
@property (nonatomic, strong) UIImageView *vipImage;
@property (nonatomic, strong) UIImageView *genderImageView;
@property (nonatomic, strong) UILabel *contentLabel;


@end

@implementation PersonalViewController


- (void)setPostId:(NSString *)postId {
    _postId = postId;
    [self netWork];
    [self secNetWork];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self createTableView];
    [self handleNavigationBar];
    [self netWork];
    [self secNetWork];
}

- (void)netWork {
    //  c=User&m=getHomePageInfo&p=%7B%22id%22%3A
    //  %2257b9a3eba9a36d645cc84e5d%22%2C%22selfId%22%3A%2257c01d33a9a36d0621c123f7%22%7D&t=t&v=v105
    //  c=User&m=getHomePageInfo&p=%7B%22id%22%3A%2257da45b7a9a36d88431dac07%22%2C%22selfId%22%3A%2257c01d33a9a36d0621c123f7%22%7D&t=t&v=v105
    //      %7B%22id%22%3A%2257b9a3eba9a36d645cc84e5d%22%2C%22selfId%22%3A%2257c01d33a9a36d0621c123f7%22%7D
    //     {"id":"57b9a3eba9a36d645cc84e5d","selfId":"57c01d33a9a36d0621c123f7"}
    // 57b9a3eba9a36d645cc84e5d
    NSString *userid = @"57c01d33a9a36d0621c123f7";
    NSString *text = [NSString stringWithFormat:@"{\"id\":\"%@\",\"selfId\":\"%@\"}", _postId, userid];
    NSString *utf8Text = [text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
    //    NSLog(@"%@", utf8Text);
    //    NSString *p = [self URLEncodedString:utf8Text];
    //    NSString *parmeters = [NSString stringWithFormat:@"c=Post&m=postDetail&p=%7B%22uid%22%3A%2257c01d33a9a36d0621c123f7%22%2C%22pid%22%3A%225723ebe4a9a36d3340a304b6%22%7D&t=t&v=v105", utf8Text];
    
    NSString *parmeters = [NSString stringWithFormat:@"c=User&m=getHomePageInfo&p=%@&t=t&v=v105", utf8Text];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *postURLString = @"http://api.zheli.io:9501/";
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    // 设置请求参数的字符串, 自定义
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
        
        return parmeters;
    }];
    // 正常post发送
    [manager POST:postURLString parameters:parmeters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.personModel = [PersonAbstractModel modelWithDic:responseObject];
        
        // 给头视图上所有的子控件赋值
        [self setUpChildrenViewData];
        // 并给头视图上的所有的子控件frame
        [self setUpAllChildrenViewFrame];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败: %@", error);
        
    }];
}

// 给头视图上所有的子控件赋值
- (void)setUpChildrenViewData {
    // 背景图片
    [_backImageViewForTableHeaderView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://qn.zheli.io/%@", _personModel.content.bgImage]]];
    
    // 头像图片
    [_headerImageButton sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://qn.zheli.io/%@", _personModel.content.avatar]] forState:UIControlStateNormal];
    
    // 达人
    if (_personModel.content.talentDays != 0) {
        NSString *totalString = [NSString stringWithFormat:@"以保持达人身份%ld天", _personModel.content.talentDays];
        NSString *string = [NSString stringWithFormat:@"%ld", _personModel.content.talentDays];
        NSMutableAttributedString *str = [self makeAutriblute:string totalString:totalString];
        _contentLabel.attributedText = str;
    }
    
    // vip
    if (_personModel.content.isTalent == YES) {
        _vipImage.image = [UIImage imageNamed:@"vipAvatar"];
    } else {
        _vipImage.hidden = YES;
    }
    
    // 用户名
    _nameLabel.text = _personModel.content.uname;
    
    // 标题
    _titleLabel.text = _personModel.content.uname;
    
    // 性别
    if ([_personModel.content.sex isEqualToString:@"1"]) {
        _genderImageView.image = [UIImage imageNamed:@"sexMale"];
    } else if ([_personModel.content.sex isEqualToString:@"2"]){
        _genderImageView.image = [UIImage imageNamed:@"sexFemale"];
        
    }
}

// 并给头视图上的所有的子控件frame
- (void)setUpAllChildrenViewFrame {
    _headerImageButton.frame = CGRectMake(ViewMargin / 2 * 3, CGRectGetMaxY(_backImageViewForTableHeaderView.frame) - SCREEN_WIDTH / 3 - 15, SCREEN_WIDTH / 3, SCREEN_WIDTH / 3);
    _vipImage.frame = CGRectMake(CGRectGetMaxX(_headerImageButton.frame) - 20, CGRectGetMaxY(_headerImageButton.frame) - 20, 24, 24);
    _maskingImageView.frame = _backViewForTableHeaderView.frame;

    CGFloat width = [SelfSizeTool selfSizeWidthWithString:_personModel.content.uname height:40 font:[UIFont systemFontOfSize:18 weight:2]];
    _nameLabel.frame = CGRectMake(CGRectGetMaxX(_headerImageButton.frame) + ViewMargin, CGRectGetMidY(_headerImageButton.frame) - 20, width, 40);
    _genderImageView.frame = CGRectMake(CGRectGetMaxX(_nameLabel.frame) + ViewMargin, CGRectGetMinY(_nameLabel.frame) + 8, 24, 24);
    _contentLabel.frame = CGRectMake(CGRectGetMinX(_nameLabel.frame), CGRectGetMaxY(_nameLabel.frame), 200, 20);

}



- (void)secNetWork {
    //  c=User&m=getHomePageInfo&p=%7B%22id%22%3A
    //  %2257b9a3eba9a36d645cc84e5d%22%2C%22selfId%22%3A%2257c01d33a9a36d0621c123f7%22%7D&t=t&v=v105
    //  c=User&m=getHomePageInfo&p=%7B%22id%22%3A%2257da45b7a9a36d88431dac07%22%2C%22selfId%22%3A%2257c01d33a9a36d0621c123f7%22%7D&t=t&v=v105
    //      %7B%22id%22%3A%2257b9a3eba9a36d645cc84e5d%22%2C%22selfId%22%3A%2257c01d33a9a36d0621c123f7%22%7D
    //     {"id":"57b9a3eba9a36d645cc84e5d","selfId":"57c01d33a9a36d0621c123f7"}
    // 57b9a3eba9a36d645cc84e5d
    NSString *userid = @"57c01d33a9a36d0621c123f7";
    NSString *text = [NSString stringWithFormat:@"{\"id\":\"%@\",\"selfId\":\"%@\"}", _postId, userid];
    NSString *utf8Text = [text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
    //    NSLog(@"%@", utf8Text);
    //    NSString *p = [self URLEncodedString:utf8Text];
    //    NSString *parmeters = [NSString stringWithFormat:@"c=Post&m=postDetail&p=%7B%22uid%22%3A%2257c01d33a9a36d0621c123f7%22%2C%22pid%22%3A%225723ebe4a9a36d3340a304b6%22%7D&t=t&v=v105", utf8Text];
    
    NSString *parmeters = [NSString stringWithFormat:@"c=User&m=getPostChannels&p=%@&t=t&v=v105", utf8Text];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *postURLString = @"http://api.zheli.io:9501/";
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    // 设置请求参数的字符串, 自定义
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
        
        return parmeters;
    }];
    // 正常post发送
    [manager POST:postURLString parameters:parmeters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSArray *array = responseObject[@"content"];
            self.personalViewModelArray = [NSMutableArray array];
            for (NSDictionary *dic in array) {
                PersonChannelContent  *channelContent = [PersonChannelContent modelWithDic:dic];
                PersonalViewModel *viewModel = [[PersonalViewModel alloc] init];
                viewModel.personalContent = channelContent;
                [_personalViewModelArray addObject:viewModel];
            }
        [_personalTableView reloadData];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败: %@", error);
    }];
}
#warning 关键字高亮
- (NSMutableAttributedString *)makeAutriblute :(NSString *)string totalString:(NSString *)totalString {
    
    NSString *title = [NSMutableString stringWithFormat:@"%@",string];
    // 找到搜索关键字在字符串中的range;
    NSRange range = [totalString rangeOfString: title];

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:totalString];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:range];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15 weight:3] range:range];
    
    return attributedString;
}


- (void)handleNavigationBar {
    // 去掉背景图片
    
    [self.view insertSubview:self.backView aboveSubview:_personalTableView];
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    _titleLabel.center = CGPointMake(SCREEN_WIDTH / 2, 42);
    _titleLabel.textAlignment = 1;
    _titleLabel.textColor = [UIColor whiteColor];
    [self.backView addSubview:_titleLabel];
    self.backView.backgroundColor = [self.backColor colorWithAlphaComponent:0];
    _titleLabel.alpha = 0;


    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 27, 30, 30)];
    [backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [self.backView addSubview:backButton];
    [backButton addTarget:self action:@selector(popViewControllerAction:) forControlEvents:UIControlEventTouchUpInside];

    UIButton *moreButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 40, 27, 30, 30)];
    [moreButton setImage:[UIImage imageNamed:@"more"] forState:UIControlStateNormal];
    [self.backView addSubview:moreButton];
    [moreButton addTarget:self action:@selector(moreAction:) forControlEvents:UIControlEventTouchUpInside];

}
// 返回上一页
- (void)popViewControllerAction: (UIButton *)backButton {
    [self.navigationController popViewControllerAnimated:YES];
}

// 更多
- (void)moreAction:(UIButton *)moreButton {
    NSLog(@"更多");
}

- (void)createTableView {
    self.personalTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _personalTableView.backgroundColor = [UIColor whiteColor];
    _personalTableView.delegate = self;
    _personalTableView.dataSource = self;
    [_personalTableView registerClass:[PersonalTableViewCell class] forCellReuseIdentifier:@"reuse"];
    [self.view addSubview:_personalTableView];
    _personalTableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    _personalTableView.tableHeaderView = [self createTableHeaderView];
}

- (UIView *)createTableHeaderView {
    // 头视图背景
    self.backViewForTableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 300)];
    self.backImageViewForTableHeaderView = [[UIImageView alloc] initWithFrame:self.backViewForTableHeaderView.bounds];

    [self.backViewForTableHeaderView addSubview:_backImageViewForTableHeaderView];
   
    self.maskingImageView = [[UIImageView alloc] init];
    _maskingImageView.image = [UIImage imageNamed:@"gradientCover"];
    [_backViewForTableHeaderView addSubview:_maskingImageView];

    
    // 头像
    self.headerImageButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _headerImageButton.layer.borderWidth = 3;
    _headerImageButton.layer.borderColor = [UIColor whiteColor].CGColor;
//    _headerImageButton.backgroundColor = [UIColor yellowColor];
    [_backViewForTableHeaderView addSubview:_headerImageButton];
    
    // 用户名
    self.nameLabel = [[UILabel alloc] init];
    _nameLabel.textColor = [UIColor whiteColor];
    _nameLabel.font = [UIFont systemFontOfSize:18 weight:2];
    [self.backViewForTableHeaderView addSubview:_nameLabel];

    // vip
    self.vipImage = [[UIImageView alloc] init];
    [self.backViewForTableHeaderView addSubview:_vipImage];
    
    // desc
    self.contentLabel = [[UILabel alloc] init];
//    _contentLabel.backgroundColor = [UIColor cyanColor];
    _contentLabel.textColor = [UIColor whiteColor];
    _contentLabel.font = TextFont;
    [self.backViewForTableHeaderView addSubview:_contentLabel];
    
    // 性别
    self.genderImageView = [[UIImageView alloc] init];
    _genderImageView.backgroundColor = [UIColor whiteColor];
    _genderImageView.layer.cornerRadius = 12;
    [_backViewForTableHeaderView addSubview:_genderImageView];
    
    
    return _backViewForTableHeaderView;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    PersonalViewModel *viewModel = _personalViewModelArray[indexPath.row];

    return viewModel.cellHeight + 10;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _personalViewModelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PersonalViewModel *viewModel = _personalViewModelArray[indexPath.row];
    PersonalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    cell.personalViewModel = viewModel;
    
    
    __weak typeof(self) weakSelf = self;
    PostsDetailViewController *postDetailVC = [[PostsDetailViewController alloc] init];
    PostVoiceViewController *voiceVC = [[PostVoiceViewController alloc] init];
    cell.cellView.postNextPage = ^(PersonChannelPosts *post){

        if ([post.postType isEqualToString:@"Voice"]) {
            [weakSelf.navigationController pushViewController:voiceVC animated:YES];
            voiceVC.postId = post.ID;
        } else {
            [weakSelf.navigationController pushViewController:postDetailVC animated:YES];
            postDetailVC.postId = post.ID;
        }
    };
    return cell;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offset_Y = scrollView.contentOffset.y;
    CGFloat alpha = (offset_Y) / 300.0f;
    self.backView.backgroundColor = [self.backColor colorWithAlphaComponent:alpha];
    self.titleLabel.alpha = alpha;
    if (offset_Y < 0) {
        CGFloat add_height = -(offset_Y);
        CGFloat scale = (300 + add_height) / 300.0f;
        self.backImageViewForTableHeaderView.frame = CGRectMake(-(SCREEN_WIDTH * scale - SCREEN_WIDTH) / 2.0f, -add_height, SCREEN_WIDTH * scale, 300 + add_height);
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
